package com.kgc.warehouse.system.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {

    //filter
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager)
    {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //创建集合、设置资源认证权限

        LinkedHashMap<String, String> map = new LinkedHashMap<>();

        map.put("/api/**","anon");
        map.put("/css/**","anon");
        map.put("/images/**","anon");
        map.put("/js/**","anon");
        map.put("/lib/**","anon");
        map.put("/extend/**","anon");
        map.put("/user/login", "anon");
        map.put("/captcha/getCaptcha","anon");

        map.put("/**","user");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return  shiroFilterFactoryBean;
    }

    //defaultWebSecurityManager

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm)
    {

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(realm);
        //记住我
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setMaxAge(60);
        cookieRememberMeManager.setCookie(cookie);
        defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager);
        return  defaultWebSecurityManager;
    }

    @Bean
    public Realm realm()
    {
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(2);
        customerRealm.setCredentialsMatcher(md5);
        return customerRealm;
    }
}
